package com.matrix.kernel.util;

import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author liuxiang
 * @email lewis_liux@hotmail.com
 * @date 2017/10/31
 * @time 15:10
 */
public class AjaxResponse {
    /**
     * ajax请求返回结果
     * @param response
     * @param type ajax返回类型 如：json、text
     * @param jsonStr ajax返回结果
     */
    public static void write(HttpServletResponse response,String type,String jsonStr){

        if(type != null && type.equals("text")){
            response.setContentType("text/plain");
        }else{
            response.setContentType("application/json");
        }

        try {
            response.getWriter().write(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ajax请求返回结果
     * @param response
     * @param jsonStr ajax返回结果
     */
    public static void write(HttpServletResponse response, String jsonStr) {
        response.setContentType("application/json");
        try {
            response.getWriter().write(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传的返回结果
     * @param response
     * @param map
     */
    public static void write(HttpServletResponse response,   Map<String, Object> map){
        response.setContentType("text/html;charset=utf-8");
        try {
            JSONObject jsonObject = JSONObject.fromObject(map);
            response.getWriter().write(jsonObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
